package com.wtf.dsp.admin.core.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.wtf.dsp.admin.core.provider.WtfDynamicDataSourceProvider;
import lombok.Data;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader;
import org.apache.velocity.util.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class VelocityConfig implements InitializingBean {

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Value("${spring.datasource.dynamic.primary}")
    private String masterDs;

    @Override
    public void afterPropertiesSet() throws Exception {
        DataSource masterDataSource = dynamicRoutingDataSource.getDataSource(masterDs);
        DataSourceResourceLoader dataSourceResourceLoader = new DataSourceResourceLoader();
        dataSourceResourceLoader.setDataSource(masterDataSource);
        ExtendedProperties loaderProp = new ExtendedProperties();
        loaderProp.setProperty("file.resource.loader.instance", dataSourceResourceLoader);
        Velocity.setExtendedProperties(loaderProp);
        Velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader");
        Velocity.setProperty("file.resource.loader.resource.datasource", "wtf");
        Velocity.setProperty("file.resource.loader.resource.table", "wtf_dsp_vm");
        Velocity.setProperty("file.resource.loader.resource.keycolumn", "vm_template");
        Velocity.setProperty("file.resource.loader.resource.templatecolumn", "vm_context");
        Velocity.setProperty("file.resource.loader.resource.timestampcolumn", "create_time");
        Velocity.init();
    }
}
